document.addEventListener('DOMContentLoaded', function() {
    const urlSettingsContainer = document.getElementById('urlSettings');
    const addUrlButton = document.getElementById('addUrlButton');
    let hasChanges = false; // Track if there are unsaved changes
    let originalSettings = []; // Store the original settings to compare with current values
    let bannerPosition = 'top-center'; // Default banner position
  
    // Load saved settings
    chrome.storage.sync.get(['urlSettings', 'bannerPosition'], function(items) {
      originalSettings = JSON.parse(JSON.stringify(items.urlSettings || [])); // Deep copy
      const urlSettings = items.urlSettings || [];
      bannerPosition = items.bannerPosition || 'top-center';
      renderUrlSettings(urlSettings);
      setupTabs();
      setupBannerPosition(bannerPosition);
      setupImportExport();
    });
  
    // Add new URL setting
    addUrlButton.addEventListener('click', function() {
      addNewUrlSetting();
    });
  
    // Save all settings
    function saveSettings() {
      const urlSettings = [];
      document.querySelectorAll('.url-setting').forEach((settingDiv, index) => {
        const urlInput = settingDiv.querySelector('.url-input');
        const warningTextInput = settingDiv.querySelector('.warning-text-input');
        const backgroundColorInput = settingDiv.querySelector('.background-color-input');
        const textColorInput = settingDiv.querySelector('.text-color-input');
        
        urlSettings.push({
          url: urlInput.value,
          warningText: warningTextInput.value,
          backgroundColor: backgroundColorInput.value,
          textColor: textColorInput.value
        });
      });
  
      // Get the selected banner position
      const selectedPosition = document.querySelector('input[name="bannerPosition"]:checked').value;
      
      chrome.storage.sync.set({
        urlSettings: urlSettings,
        bannerPosition: selectedPosition
      }, function() {
        // Update original settings and reset change tracking
        originalSettings = JSON.parse(JSON.stringify(urlSettings));
        bannerPosition = selectedPosition;
        hasChanges = false;
        updateSaveButton();
        alert('Settings saved!');
      });
    }
  
    // Update save button visibility and text based on changes
    function updateSaveButton() {
      const existingSaveButtons = document.querySelectorAll('.save-changes-button');
      const urlConfigButtonContainer = document.querySelector('#url-config .button-container');
      const bannerConfigButtonContainer = document.querySelector('#banner-config .button-container');
      
      // Create button containers if they don't exist
      if (!urlConfigButtonContainer) {
        const urlConfigTab = document.getElementById('url-config');
        const container = document.createElement('div');
        container.className = 'button-container';
        urlConfigTab.appendChild(container);
      }
      
      if (!bannerConfigButtonContainer) {
        const bannerConfigTab = document.getElementById('banner-config');
        const container = document.createElement('div');
        container.className = 'button-container';
        bannerConfigTab.appendChild(container);
      }
      
      const urlConfigButtonContainerUpdated = document.querySelector('#url-config .button-container');
      const bannerConfigButtonContainerUpdated = document.querySelector('#banner-config .button-container');
      
      if (hasChanges) {
        // Remove existing save buttons
        existingSaveButtons.forEach(button => button.remove());
        
        // Create new save buttons for both tabs
        const saveButton1 = document.createElement('button');
        saveButton1.textContent = 'Save';
        saveButton1.className = 'save-changes-button';
        saveButton1.addEventListener('click', saveSettings);
        urlConfigButtonContainerUpdated.appendChild(saveButton1);
        
        const saveButton2 = document.createElement('button');
        saveButton2.textContent = 'Save';
        saveButton2.className = 'save-changes-button';
        saveButton2.addEventListener('click', saveSettings);
        bannerConfigButtonContainerUpdated.appendChild(saveButton2);
      } else {
        // Remove all save buttons
        existingSaveButtons.forEach(button => button.remove());
      }
    }
  
    // Check if settings have changed compared to original
    function checkForChanges() {
      const currentSettings = [];
      document.querySelectorAll('.url-setting').forEach((settingDiv, index) => {
        const urlInput = settingDiv.querySelector('.url-input');
        const warningTextInput = settingDiv.querySelector('.warning-text-input');
        const backgroundColorInput = settingDiv.querySelector('.background-color-input');
        const textColorInput = settingDiv.querySelector('.text-color-input');
        
        currentSettings.push({
          url: urlInput.value,
          warningText: warningTextInput.value,
          backgroundColor: backgroundColorInput.value,
          textColor: textColorInput.value
        });
      });
  
      if (currentSettings.length !== originalSettings.length) {
        hasChanges = true;
      } else {
        hasChanges = false;
        for (let i = 0; i < currentSettings.length; i++) {
          if (currentSettings[i].url !== originalSettings[i].url ||
              currentSettings[i].warningText !== originalSettings[i].warningText ||
              currentSettings[i].backgroundColor !== originalSettings[i].backgroundColor ||
              currentSettings[i].textColor !== originalSettings[i].textColor) {
            hasChanges = true;
            break;
          }
        }
      }
    }
  
    // Render URL settings
    function renderUrlSettings(urlSettings) {
      urlSettingsContainer.innerHTML = '';
      
      urlSettings.forEach((setting, index) => {
        addUrlSettingToDOM(setting, index);
      });
      
      // Initially check for changes after rendering
      setTimeout(checkForChanges, 0);
    }
  
    // Add new empty URL setting
    function addUrlSettingToDOM(setting = {}, index = null) {
      const settingRow = document.createElement('tr');
      settingRow.className = 'url-setting';
      
      settingRow.innerHTML = `
        <td><input type="text" class="input-field url-input" value="${setting.url || ''}"></td>
        <td><input type="text" class="input-field warning-text-input" value="${setting.warningText || ''}"></td>
        <td><input type="color" class="background-color-input" value="${setting.backgroundColor || '#ff0000'}"></td>
        <td><input type="color" class="text-color-input" value="${setting.textColor || '#ffffff'}"></td>
        <td><button class="delete-button" title="Delete">Delete</button></td>
      `;
      
      // Add input event listeners to track changes
      const urlInput = settingRow.querySelector('.url-input');
      const warningTextInput = settingRow.querySelector('.warning-text-input');
      const backgroundColorInput = settingRow.querySelector('.background-color-input');
      const textColorInput = settingRow.querySelector('.text-color-input');
      
      urlInput.addEventListener('input', function() {
        hasChanges = true;
        updateSaveButton();
      });
      
      warningTextInput.addEventListener('input', function() {
        hasChanges = true;
        updateSaveButton();
      });
      
      backgroundColorInput.addEventListener('input', function() {
        hasChanges = true;
        updateSaveButton();
      });
      
      if (textColorInput) {
        textColorInput.addEventListener('input', function() {
          hasChanges = true;
          updateSaveButton();
        });
      }
      
      // Add delete functionality
      settingRow.querySelector('.delete-button').addEventListener('click', function() {
        settingRow.remove();
        hasChanges = true;
        updateSaveButton();
      });
      
      // If this is a new setting, add it before the save button
      if (index === null) {
        const saveButton = urlSettingsContainer.querySelector('.save-changes-button');
        if (saveButton) {
          urlSettingsContainer.insertBefore(settingRow, saveButton);
        } else {
          urlSettingsContainer.appendChild(settingRow);
        }
      } else {
        urlSettingsContainer.appendChild(settingRow);
      }
    }
    
    // Add new empty URL setting
    function addNewUrlSetting() {
      // Get the current active tab's URL and extract domain or IP+port
      chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        if (tabs[0]) {
          const url = new URL(tabs[0].url);
          const domainOrIP = url.hostname + (url.port ? ':' + url.port : '');
          const setting = {
            url: domainOrIP
          };
          addUrlSettingToDOM(setting);
          hasChanges = true;
          updateSaveButton();
        } else {
          addUrlSettingToDOM();
          hasChanges = true;
          updateSaveButton();
        }
      });
    }
    
    // Set up tab functionality
    function setupTabs() {
      const tabButtons = document.querySelectorAll('.tab-button');
      const tabPanes = document.querySelectorAll('.tab-pane');
      
      tabButtons.forEach(button => {
        button.addEventListener('click', function() {
          const tabId = this.getAttribute('data-tab');
          
          // Remove active class from all buttons and panes
          tabButtons.forEach(btn => btn.classList.remove('active'));
          tabPanes.forEach(pane => pane.classList.remove('active'));
          
          // Add active class to clicked button and corresponding pane
          this.classList.add('active');
          document.getElementById(tabId).classList.add('active');
        });
      });
    }
    
    // Set up banner position radio buttons
    function setupBannerPosition(position) {
      const radioButtons = document.querySelectorAll('input[name="bannerPosition"]');
      radioButtons.forEach(radio => {
        if (radio.value === position) {
          radio.checked = true;
        }
        
        radio.addEventListener('change', function() {
          if (this.checked) {
            hasChanges = true;
            updateSaveButton();
          }
        });
      });
    }
    
    // Export settings function
    function exportSettings() {
      chrome.storage.sync.get(['urlSettings', 'bannerPosition'], function(items) {
        const settingsToExport = {
          urlSettings: items.urlSettings || [],
          bannerPosition: items.bannerPosition || 'top-center'
        };
        
        const jsonStr = JSON.stringify(settingsToExport, null, 2);
        const textArea = document.createElement('textarea');
        textArea.value = jsonStr;
        textArea.style.position = 'fixed';
        textArea.style.top = '0';
        textArea.style.left = '0';
        textArea.style.width = '100%';
        textArea.style.height = '100%';
        textArea.style.fontSize = '12px';
        textArea.style.padding = '10px';
        textArea.style.boxSizing = 'border-box';
        textArea.style.zIndex = '9999';
        textArea.setAttribute('readonly', true);
        
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        
        try {
          const successful = document.execCommand('copy');
          if (successful) {
            alert('Configuration copied to clipboard! Paste it somewhere to save it.');
          } else {
            // Fallback: show in a dialog
            const result = prompt('Copy your configuration below:', jsonStr);
          }
        } catch (err) {
          // Fallback: show in a dialog
          const result = prompt('Copy your configuration below:', jsonStr);
        }
        
        document.body.removeChild(textArea);
      });
    }
    
    // Import settings function
    function importSettings() {
      chrome.storage.sync.get(['urlSettings', 'bannerPosition'], function(items) {
        const currentSettings = {
          urlSettings: items.urlSettings || [],
          bannerPosition: items.bannerPosition || 'top-center'
        };
        
        const currentJsonStr = JSON.stringify(currentSettings, null, 2);
        const newJsonStr = prompt('Paste your new configuration here:', currentJsonStr);
        
        if (newJsonStr) {
          try {
            const newSettings = JSON.parse(newJsonStr);
            
            if (!Array.isArray(newSettings.urlSettings) || typeof newSettings.bannerPosition !== 'string') {
              alert('Invalid configuration format!');
              return;
            }
            
            // Save the new settings
            chrome.storage.sync.set({
              urlSettings: newSettings.urlSettings,
              bannerPosition: newSettings.bannerPosition
            }, function() {
              // Update original settings and reset change tracking
              originalSettings = JSON.parse(JSON.stringify(newSettings.urlSettings));
              bannerPosition = newSettings.bannerPosition;
              hasChanges = false;
              updateSaveButton();
              
              alert('Settings imported successfully!');
              
              // Reload the page to reflect the new settings
              window.location.reload();
            });
            
          } catch (e) {
            alert('Invalid JSON format! Please check your configuration.');
          }
        }
      });
    }
    
    // Set up import/export buttons
    function setupImportExport() {
      const exportButton = document.getElementById('exportSettingsButton');
      const importButton = document.getElementById('importSettingsButton');
      
      if (exportButton) {
        exportButton.addEventListener('click', exportSettings);
      }
      
      if (importButton) {
        importButton.addEventListener('click', importSettings);
      }
    }
  });